<?php

namespace App\Http\Controllers;

use App\Exceptions\ExceptionApi;
use App\Http\Response\VideoResponse;
use App\Models\User;
use App\Models\Video;
use App\Services\Logger;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Services\Response as ResponseService;

class VideoController extends Controller
{

    private $video_weight;
    private $new_last_id;
    private $recommend_last_id;
    private $normal_last_id;
    private $page;
    private $limit;
    private $total;

    private static function getMaxPage($total, $limit){
        $lastCount = $total % $limit;
        $page = intval($total/$limit);
        return $lastCount>0 ? $page+1 : $page;
    }
    private function hasData(){
        if($this->page > self::getMaxPage($this->total, $this->limit)){
            return false;
        }
        return true;
    }


    /**
     * @api {GET} /api/video 获取短视频详情
     * @apiGroup 短视频
     * @apiParamExample {x-www-form-urlencoded} 参数请求示例:
     * ?id=1
     * @apiDescription 通过视频ID获取短视频详情
     * @apiUse PublicCommonBlock
     * @apiParam {Integer} id 短视频ID
     * @apiSuccess {Integer} data.id 视频资源ID
     * @apiSuccess {Integer} data.user_id 视频发布者用户ID
     * @apiSuccess {String} data.url 视频资源链接
     * @apiSuccess {String} data.image 视频封面图片
     * @apiSuccess {String} data.title 视频标题
     * @apiSuccess {String} data.author_img 作者头像
     * @apiSuccess {Integer} data.likes_num 点赞数
     * @apiSuccess {Integer} data.review_num 评论数
     * @apiSuccess {Integer} data.has_follow_author 是否已关注作者
     * @apiSuccess {Integer} data.has_like 是否已点赞
     * @apiSuccess {String} data.created_at 视频创建时间
     * @apiSuccessExample {json} 成功相应示例
     * {"code":200,"msg":"success","data":{"id":42,"user_id":1,"url":"http:\/\/frp.catmes.com\/uploads\/videos\/2021_05_21_17_13_26_aGV93rTz.mp4","is_recommend":0,"image":"http:\/\/frp.catmes.com\/uploads\/videos\/2021_05_21_17_13_26_aGV93rTz.jpg","title":"#c\u7f57 #\u66fc\u8054 \u65f6\u671f\u65e0\u89e3\u7535\u68af\u843d\u53f6\u7403#\u82f1\u8d85 \u5f17\u683c\u68ee\u76f4\u8a00\uff0c\u6ca1\u6709\u95e8\u5c06\u6251\u7684\u6389","author_img":"https:\/\/dy.zq.xiantou.com\/uploads\/default.png","likes_num":397,"video_weight":0,"review_num":0,"has_follow_author":0,"has_like":0,"created_at":"2021-05-21 17:13:26"}}
     * @throws ExceptionApi
     */
    public function detail(Request $request):Response{
        if(config('app.env')!='production'){
            ResponseService::setNotCORS($request);
        }
        $id = $request->input('id');
        if(!$id){
            throw new ExceptionApi('缺少必要参数');
        }
        $model = Video::query()->where('id', "=", $id)->first();
        if(empty($model)){
            throw new ExceptionApi('视频不存在');
        }
        return $this->success(VideoResponse::toArray($model));
    }

    /**
     * @api {GET} /api/home/videos 获取短视频列表
     * @apiGroup 短视频
     * @apiParamExample {x-www-form-urlencoded} 参数请求示例:
     * ?page=2&limit=3
     * @apiDescription 获取短视频列表
     * @apiUse PublicCommonBlock
     * @apiParam {String} token 用户身份令牌 选填
     * @apiParam {Integer} video_weight=0 最近看过的新手视频库权重
     * @apiParam {Integer} new_last_id=0 看过的最近的近期视频ID
     * @apiParam {Integer} recommend_last_id=0 看过的最近的推荐视频ID
     * @apiParam {Integer} normal_last_id=0 看过的最近的普通视频ID
     * @apiParam {Integer} page=1 页码 选填
     * @apiParam {Integer} limit=15 每页显示的数据条数 选填
     * @apiSuccess {Number} data.total 短视频总数
     * @apiSuccess {Number} data.current_page 当前分页
     * @apiSuccess {Object[]} data.items 短视频列表详情
     * @apiSuccess {Integer} data.items.id 视频资源ID
     * @apiSuccess {Integer} data.items.user_id 视频发布者用户ID
     * @apiSuccess {String} data.items.url 视频资源链接
     * @apiSuccess {String} data.items.image 视频封面图片
     * @apiSuccess {String} data.items.title 视频标题
     * @apiSuccess {String} data.items.author_img 作者头像
     * @apiSuccess {Integer} data.items.likes_num 点赞数
     * @apiSuccess {Integer} data.items.review_num 评论数
     * @apiSuccess {Integer} data.items.has_follow_author 是否已关注作者
     * @apiSuccess {Integer} data.items.has_like 是否已点赞
     * @apiSuccess {String} data.items.created_at 视频创建时间
     * @apiSuccessExample {json} 成功相应示例
     * {"code":200,"msg":"success","data":{"total":4,"current_page":2,"items":[{"url":"http:\/\/tikball.test\/uploads\/videos\/b.mp4","image":"http:\/\/tikball.test\/uploads\/videos\/bb.png","title":"fda","author_img":"https:\/\/dy.zq.xiantou.com\/uploads\/default.png","likes_num":0,"review_num":0,"has_follow_author":0,"has_like":0,"created_at":"2021-05-17 14:58:51"},{"url":"http:\/\/tikball.test\/uploads\/videos\/a.mp4","image":"http:\/\/tikball.test\/uploads\/videos\/a.jpg","title":"fda","author_img":"https:\/\/dy.zq.xiantou.com\/uploads\/default.png","likes_num":0,"review_num":0,"has_follow_author":0,"has_like":0,"created_at":"2021-05-17 14:58:47"}]}}
     */
    public function index(Request $request) :Response
    {
        $page = 1;
        if($request->input('new_last_id', null)===null){
            $page = (int) $request->input('page',1);
            if(empty($page)){
                $page=1;
            }
        }

        $limit = (int) $request->input('limit',10);
        if(empty($limit)){
            $limit = 10;
        }

        $this->page = $page;
        $this->limit = $limit;

        $video_weight = (int) $request->input('video_weight', 0);
        $new_last_id = (int) $request->input('new_last_id',0);
        $recommend_last_id = (int) $request->input('recommend_last_id', 0);
        $normal_last_id = (int) $request->input('normal_last_id', 0);

        $this->video_weight = $video_weight;
        $this->new_last_id = $new_last_id;
        $this->recommend_last_id = $recommend_last_id;
        $this->normal_last_id = $normal_last_id;

        if($video_weight>0){
            $query = Video::getQuery();
            $query->where('weight', ">", 0);
            $query = $this->getQueryByWeight($query, $video_weight);
            if($query){
                if($this->hasData()){
                    return $this->getVideosByQuery($query, $request, 'video_weight');
                }
            }
        }


        $baseQuery = Video::getQuery()->where("weight", '=',0);

        $query = clone $baseQuery;
        $timestamp = time();
        // 最近视频取2天前至今天
        $beginDayTimestamp = $timestamp - 3600*24*2;
        $date = date('Y-m-d', $beginDayTimestamp);
        $query->where('created_at', ">", $date);
        $query = $this->getQueryByLastId($query, $new_last_id);
        if($query){
            if($this->hasData()){
                return $this->getVideosByQuery($query, $request, 'new_last_id');
            }
        }

        // 近期视频已看完或数据为空 查询推荐视频数据
        $query = clone $baseQuery;
        $query->where('is_recommend', '=', 1);
        $query = $this->getQueryByLastId($query, $recommend_last_id);
        if($query){
            if($this->hasData()){
                return $this->getVideosByQuery($query, $request, 'recommend_last_id');
            }
        }

        // 推荐视频已看完
        $query = clone $baseQuery;
        $query = $this->getQueryByLastId($query, $normal_last_id);
        if($query){
            if($this->hasData()){
                return $this->getVideosByQuery($query, $request, 'normal_last_id');
            }
        }

        $query = clone $baseQuery;
        $this->page = 1;
        $query = $this->getQueryByLastId($query, 0);
        return $this->getVideosByQuery($query, $request, 'normal_last_id');
    }

    protected function getQueryByLastId(Builder $query, $lastId){
        // 近期未上传新的视频 | 最近视频已看完
        // 播放精选视频
        // 播放普通视频
        $total = $query->count();
        $this->total = $total;
        if($total>0){
            $newBeginIdRes = $query->min('id');
            if($lastId>=$newBeginIdRes){
                $query->where('id', '>', $lastId);
                $total = $query->count();
                if($total > 0){
                    $this->total = $total;
                    return $query;
                }
                return null;
            }
            return $query;
        }
        return null;
    }

    protected function getQueryByWeight(Builder $query, $weight){
        // 新手播放视频库
        $total = $query->count();
        $this->total = $total;
        if($total>0){
            $minWeight = $query->min('weight');
            if($weight>$minWeight){
                $query->where('weight', '<', $weight)->orderByDesc('weight');
                $total = $query->count();
                if($total > 0){
                    $this->total = $total;
                    return $query;
                }
                return null;
            }
            return null;
        }
        return null;
    }



    protected function getVideosByQuery(Builder $query, Request $request, $type='normal_last_id'){
        $page = $this->page;
        $limit = $this->limit;

        $videos = $query->paginate($limit, ["*"], 'page', $page);
        $total = $videos->total();
        $items = $videos->items();

        $currentPage = $videos->currentPage();

        //TODO 根据token获取user 得出 has_follow_author
        $token = $request->input('token');
        $likeVideoIds = [];
        if($token){
            /* @var User $user */
            $user = User::findByApiToken($token);
            $likeVideoIds = $user->getLikeVideoIds();
        }
        $lastId = 0;
        $weight = 0;
        $videosItems = VideoResponse::getItemsList($items, $likeVideoIds, $lastId, $weight);

        $data = [
            'video_weight' => $this->video_weight,
            'new_last_id' => $this->new_last_id,
            'recommend_last_id' => $this->recommend_last_id,
            'normal_last_id' => $this->normal_last_id,
        ];
        $data['total'] = $total;
        $data['current_page'] = $currentPage;
        $data['items'] = $videosItems;

        if($type=='video_weight'){
            $data[$type] = $weight;
        }else{
            $data[$type] = $lastId;
        }


        return $this->success($data);
    }

}
